﻿namespace WMS6.Web.Common
{
    using System;
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Web;
    using System.Web.UI.HtmlControls;
    using WMS6.Web;

    public class TemplateDownload : BasePage
    {
        protected HtmlForm form1;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(base.Request.QueryString["type"]))
            {
                string path = string.Empty;
                string fileName = string.Empty;
                switch (base.Request.QueryString["type"])
                {
                    case "CUSTOMER":
                        path = base.Server.MapPath("../ImportTemplate/Customer.csv");
                        fileName = "Customer.csv";
                        break;

                    case "CARRIER":
                        path = base.Server.MapPath("../ImportTemplate/Carrier.csv");
                        fileName = "Carrier.csv";
                        break;

                    case "BILLINGENTITY":
                        path = base.Server.MapPath("../ImportTemplate/BillingEntity.csv");
                        fileName = "BillingEntity.csv";
                        break;

                    case "VENDOR":
                        path = base.Server.MapPath("../ImportTemplate/Vendor.csv");
                        fileName = "Vendor.csv";
                        break;

                    case "SKU":
                        if (!(base.UserInfo.IsGlobal == "Y"))
                        {
                            path = base.Server.MapPath("../ImportTemplate/SKU_WH.csv");
                            fileName = "SKU_WH.csv";
                            break;
                        }
                        path = base.Server.MapPath("../ImportTemplate/SKU.csv");
                        fileName = "SKU.csv";
                        break;

                    case "LOCATION":
                        path = base.Server.MapPath("../ImportTemplate/Location.csv");
                        fileName = "Location.csv";
                        break;

                    case "RECEIPTDETAIL":
                        path = base.Server.MapPath("../ImportTemplate/ASN.csv");
                        fileName = "ASN.csv";
                        break;

                    case "SHIPPINGORDERDETAIL":
                        path = base.Server.MapPath("../ImportTemplate/SO.csv");
                        fileName = "SO.csv";
                        break;

                    case "OWNER":
                        path = base.Server.MapPath("../ImportTemplate/Owner.csv");
                        fileName = "Owner.csv";
                        break;

                    case "ALTERNATESKU":
                        path = base.Server.MapPath("../ImportTemplate/AlternateSKU.csv");
                        fileName = "AlternateSKU.csv";
                        break;

                    case "SHIPPINGORDER":
                        path = base.Server.MapPath("../ImportTemplate/ShippingOrder.csv");
                        fileName = "ShippingOrder.csv";
                        break;

                    case "SALESORDERDETAIL":
                        path = base.Server.MapPath("../ImportTemplate/SalesOrderDetail.csv");
                        fileName = "SalesOrderDetail.csv";
                        break;

                    case "PURCHASEORDERDETAIL":
                        path = base.Server.MapPath("../ImportTemplate/PurchaseOrderDetail.csv");
                        fileName = "PurchaseOrderDetail.csv";
                        break;

                    case "MOVEMENTDETAIL":
                        path = base.Server.MapPath("../ImportTemplate/MovementDetail.csv");
                        fileName = "MovementDetail.csv";
                        break;
                }
                ResponseFile(this.Page.Request, this.Page.Response, fileName, path, 0xfa000);
                base.Response.Write("<script language=javascript>window.opener=null;window.close();</script>");
            }
        }

        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;
                    double pack = 10240.0;
                    int sleep = ((int) Math.Floor((double) ((1000.0 * pack) / ((double) _speed)))) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 0xce;
                        startBytes = Convert.ToInt64(_Request.Headers["Range"].Split(new char[] { '=', '-' })[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, Encoding.UTF8));
                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = ((int) Math.Floor((double) (((double) (fileLength - startBytes)) / pack))) + 1;
                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}

